package com.lsh.controller;

import com.lsh.entity.Fastdfsfile;
import com.lsh.service.FileService;
import com.lsh.unit.FastDFSUtil;
import com.lsh.unit.ResultObject;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/9/1 10:44 下午
 * @desc ：
 */
@Slf4j
@RequestMapping("/fastdfs")
@Controller
public class FileController {
    @Autowired
    FileService fileService;

    @ResponseBody
    @GetMapping("/monitor")
    public ResultObject isMonitor(){
        return new ResultObject("0000","查询成功",null);
    }

    @GetMapping("/look")
    public String look(HttpServletRequest request, HttpServletResponse response,String furl) throws UnsupportedEncodingException {
        log.info("查看URL："+furl);
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        return "redirect:"+furl;
    }

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws Exception {
        String upload = FastDFSUtil.upload(file);
        String data ="http://wangyitong.club/"+upload;
        Fastdfsfile fastdfsfile = new Fastdfsfile();
        fastdfsfile.setName(file.getOriginalFilename());
        fastdfsfile.setUrl(data);
        String fileName = file.getOriginalFilename();
        // 获得文件后缀
        String[] split = fileName.split("\\.");
        String suffix = split[1];
        if (suffix != null){
            if ("mp3".equals(suffix)){
                fastdfsfile.setIsMusic("0");
            }
        }
        fileService.saveFile(fastdfsfile);
        return "redirect:/fastdfs/searchAndPage";
    }

    @GetMapping("/findAll")
    public String findAllFile(Model model){
        List<Fastdfsfile> fastdfsfiles = fileService.finfAll();
        model.addAttribute("fastdfsfiles",fastdfsfiles);
        return "Thymeleaf1";
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response,String fid) throws IOException, MyException {
        //http://116.62.13.104/group1/M00/00/00/rB52RF9PPHiAYshEAACs3GObAOw25.jpeg
        String substring = fid.substring(21);//   group1/M00/00/00/rB52RF9PPHiAYshEAACs3GObAOw25.jpeg
        String[] split = substring.split("\\.");
        String type = split[1];
        System.out.println("type :"+type);
        System.out.println("substring :"+substring);
        byte[] download = FastDFSUtil.download(substring);
        String nameByUrl = fileService.findNameByUrl(fid);//   教我Java的事就拜托了.jpg
        String[] split1 = nameByUrl.split("\\.");
        String name = split1[0];//教我Java的事就拜托了
        System.out.println("fileService.findNameByUrl() :"+nameByUrl);
        System.out.println("name :"+name);
        String filename = URLEncoder.encode(name, "utf-8");
        // 浏览器响应下载弹框
        response.setHeader("Content-disposition", "attachment;filename="+filename+"."+type);
        response.setContentType("image/"+type);
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(download); // 输出数据
        outputStream.flush();
        outputStream.close();
    }
    /**
     * 常见的响应文件格式
     * 常见的媒体格式类型如下：
     *
     *     text/html ： HTML格式
     *     text/plain ：纯文本格式
     *     text/xml ：  XML格式
     *     image/gif ：gif图片格式
     *     image/jpeg ：jpg图片格式
     *     image/png：png图片格式
     *    以application开头的媒体格式类型：
     *
     *    application/xhtml+xml ：XHTML格式
     *    application/xml     ： XML数据格式
     *    application/atom+xml  ：Atom XML聚合格式
     *    application/json    ： JSON数据格式
     *    application/pdf       ：pdf格式
     *    application/msword  ： Word文档格式
     *    application/octet-stream ： 二进制流数据（如常见的文件下载）
     *    application/x-www-form-urlencoded ： <form encType=””>中默认的encType，form表单数据被编码为key/value格式发送到服务器（表单默认的提交数据的格式）
     */
    @GetMapping("/delete")
    public String del(Integer fid,String furl) throws IOException, MyException {
        log.info("要删除的文件id是："+fid);
        log.info("要删除的文件url是："+furl);//http://116.62.13.104/group1/M00/00/00/rB52RF9O8fyAeF36AEfLSmvPv58455.png
        String substring = furl.substring(21);//group1/M00/00/00/rB52RF9O8fyAeF36AEfLSmvPv58455.png
        fileService.delFile(fid);
        FastDFSUtil.delFastDFSFile(substring);
//        return "redirect:http://wangyitong.club:8081/fastdfs/findAll";
        return "redirect:/fastdfs/searchAndPage";
    }

    /**
     * 条件查询
     */
    @PostMapping("/search")
    public String search(String searchname,Model model){
        System.out.println("filename:"+searchname);
        List<Fastdfsfile> lists = fileService.search(searchname);
        model.addAttribute("fastdfsfiles",lists);
        model.addAttribute("searchname",searchname);
        return "Thymeleaf1";
    }

    /**
     * 条件分页查询
     * @return
     */
    @GetMapping("/searchAndPage")
    public String pege(String searchname,Model model,String pageNum){
        System.out.println("searchname:"+searchname);
        if ("null".equals(searchname)){
            searchname = null;
        }
        int pegeSize = 10;
        if ( pageNum ==null){
            pageNum = "1";
        }
        int parseInt = Integer.parseInt(pageNum);
        if (parseInt < 1){
            parseInt = 1;
        }
        Page pageData = fileService.searchAndPage(searchname, parseInt, pegeSize);
        // int getTotalElements() 获得总记录数
        long totalElements = pageData.getTotalElements();
        // int getTotalPages  获得总页数
        int totalPages = pageData.getTotalPages();
        // List getContent()       获得查询数据
        List content = pageData.getContent();
        model.addAttribute("searchname",searchname);
        model.addAttribute("fastdfsfiles",content);
        //当前页
        model.addAttribute("pageNo",pageNum);
        //总页数
        model.addAttribute("totalPages",totalPages);
        //总条数
        model.addAttribute("totalElements",totalElements);
        model.addAttribute("pageData",pageData);
        System.out.println("当前页:"+pageNum+"   总页数："+totalPages+"    总条数："+totalElements);

        return "Thymeleaf1";
    }


}
